package com.xu.controller;

import com.sun.org.apache.xpath.internal.operations.Mod;
import com.xu.mapper.CartMapper;
import com.xu.mapper.ProductMapper;
import com.xu.pojo.Cart;
import com.xu.pojo.Product;
import com.xu.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
public class CartController {

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private ProductService productService;

    @Autowired
    private ProductMapper productMapper;

    @RequestMapping("/addCart/{pid}/{uid}")
    public String addCart(@PathVariable("pid") int pid, @PathVariable("uid")int uid, Model model)
    {
        int numByUid = cartMapper.getNumByUid(uid);
        System.out.println(numByUid);
        int numByUidAndPid = cartMapper.getNumByUidAndPid(pid, uid);
        if (numByUidAndPid!=0)
        {
            List<Product> products = productService.queryAllProduct();
            model.addAttribute("prducts", products);
            model.addAttribute("msg2", "购物车中商品已存在，请勿反复添加");
            System.out.println("购物车中商品已存在，请勿反复添加");
            //查询购物车
            List<Cart> carts = cartMapper.queryCartByUid(uid);
            model.addAttribute("carts", carts);

            List<Product> products1 = productMapper.randomSelectProduct();
            model.addAttribute("products1", products1);

            return "index-2";
        }
        else
        {
            Cart cart = new Cart();
            cart.setPid(pid);
            cart.setUid(uid);
            cartMapper.addCart(cart);
            List<Product> products = productService.queryAllProduct();
            model.addAttribute("prducts", products);
            //查询购物车
            List<Cart> carts = cartMapper.queryCartByUid(uid);
            model.addAttribute("carts", carts);

            List<Product> products1 = productMapper.randomSelectProduct();
            model.addAttribute("products1", products1);

            return "index-2";
        }
    }
    @RequestMapping("/toCart/{uid}")
    public String toCart(Model model,@PathVariable("uid")int uid)
    {
        List<Cart> carts = cartMapper.queryCartByUid(uid);
        model.addAttribute("carts", carts);
        return "/user/cart";
    }

    @RequestMapping("/cartAdd")
    public String cartAdd(Cart cart1)
    {
        System.out.println("++++++++++++++++++进入方法");
        System.out.println(cart1);
//        for (Cart cart : carts) {
//            System.out.println(cart.toString());
//        }
        return "/user/cart";
    }

}
